package com.kpx.app.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.kpx.app.Application;
import com.kpx.app.R;
import com.kpx.app.bean.ChoosableImage;
import com.kpx.app.bean.ImageBean;
import com.kpx.app.configs.Constants;
import com.kpx.app.thirdparty.bugly.CrashReporterUtils;
import com.kpx.app.utils.datautils.FileUtils;
import com.kpx.app.utils.datautils.LogUtils;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ImageUtils {
    public static final int CROP_IMAGE_SIZE = 300; // 截图图片大小px
    private final static String TAG = ImageUtils.class.getSimpleName();
    public static String TEMP_PHOTO_FILE_NAME;
    private static File mFileTemp;


    public static ImageSize setImageSize(int width, int height) {
        return new ImageSize(width, height);
    }

    /**
     * 获取相机拍照绝对路径
     */
    public static String getCaptureImageAbsolutePath(Context context, Uri uri) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        String imagePath = null;
        if (cursor != null && cursor.moveToFirst()) {
            imagePath = "file:///" + cursor.getString(cursor.getColumnIndex("_data"));// 获取绝对路径
        }
        return imagePath;
    }

    /**
     * 获取指定大小图片(根据阿里云图片服务器说明)
     *
     * @param width   宽度
     * @param height  高度
     * @param quality 图片质量
     * @return
     */
    public static String getSpecifiedSizeImageUrl(String url, int width, int height, int quality) {
        return url + "@" + width + "w_" + height + "h_" + quality + "q_1e_1x_1o.jpg";
    }

    public static String getSpecifiedSizeImageUrl(String url, int size) {
        return url + "@" + size + "w_" + size + "h_100q_1e_1x_1o.jpg";
    }

    /**
     * 初始化IamgeLoader
     *
     * @param drawableId     默认图片id
     * @param failDrawableId 加载失败显示图片的id
     * @param cacheOnDisk    是否缓存在硬盘
     * @param cacheInMemory  是否缓存在内存
     */
    public static DisplayImageOptions initImageLoader(int drawableId, int failDrawableId, boolean cacheOnDisk, boolean cacheInMemory) {
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        if (drawableId != 0) {
            builder.showImageForEmptyUri(drawableId);
        }
        if (failDrawableId != 0)
            builder.showImageOnFail(failDrawableId);
        builder.resetViewBeforeLoading(true).cacheOnDisk(cacheOnDisk).cacheInMemory(cacheInMemory).imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(false).displayer(new FadeInBitmapDisplayer(300));
        return builder.build();
    }

    /**
     * 初始化IamgeLoader
     *
     * @param drawableId     默认图片id
     * @param failDrawableId 加载失败显示图片的id
     * @param cacheOnDisk    是否缓存在硬盘
     * @param cacheInMemory  是否缓存在内存
     */
    public static DisplayImageOptions initImageLoader(int drawableId, int failDrawableId, boolean cacheOnDisk, boolean cacheInMemory, int displayer) {
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        if (drawableId != 0) {
            builder.showImageForEmptyUri(drawableId);
        }
        if (failDrawableId != 0)
            builder.showImageOnFail(failDrawableId);
        builder.resetViewBeforeLoading(true).cacheOnDisk(cacheOnDisk).cacheInMemory(cacheInMemory).imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(false).displayer(new FadeInBitmapDisplayer(displayer));
        return builder.build();
    }

    /**
     * 获取手机相册中的图片
     */
    public static List<String> getAlumbImages(Context context) {
        //获取相册图片，按照时间排序
        List<String> imagePaths = new ArrayList<String>();
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Images.ImageColumns.MIME_TYPE, MediaStore.Images.ImageColumns.DATA};
        String order = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"; // 按时间排序
        Cursor cursor = resolver.query(uri, projection, null, null, order);
        //        Log.e("ImageUtil", "count = " + cursor.getCount());
        while (cursor.moveToNext()) {
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
            //            Log.e("ImageUtil", "path = " + path);
            if (!TextUtils.isEmpty(path))
                imagePaths.add(path);
        }
        return imagePaths;
    }

    /**
     * 将相册中的图片uri转换路径
     */
    public static List<String> uri2Path(List<String> alumbImageList) {
        List<String> pathList = new ArrayList<String>();
        for (String uri : alumbImageList) {
            String imagePath = new String("file:/" + uri);
            pathList.add(imagePath);
        }
        return pathList;
    }

    /**
     * 打开相册并回调
     */
    public static void openGalleryForResult(Fragment activity, int requestCode) {
        if (null == activity || null == activity.getActivity()) {
            return;
        }
        PackageManager pm = activity.getActivity().getPackageManager();
        initCropFile();
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        if (photoPickerIntent.resolveActivity(pm) != null) {
            activity.startActivityForResult(photoPickerIntent, requestCode);
        }
    }

    /**
     * 打开相册并回调
     */
    public static void openGalleryForResult(Context context, int requestCode) {
        if (null == context) {
            return;
        }
        PackageManager pm = context.getPackageManager();
        initCropFile();
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        if (photoPickerIntent.resolveActivity(pm) != null) {
            ((Activity) context).startActivityForResult(photoPickerIntent, requestCode);
        }
    }

    /**
     * 初始化截图文件
     */
    public static void initCropFile() {
        TEMP_PHOTO_FILE_NAME = StringUtil.getUniqueString() + Constants.IMAGE_FILE_SUFFIX;
        mFileTemp = new File(FileUtils.getTempCacheDir(), TEMP_PHOTO_FILE_NAME);
//        mFileTemp = new File(FileUtils.getTempCacheDir(), TEMP_PHOTO_FILE_NAME);

        try {
            String state = Environment.getExternalStorageState();
            TEMP_PHOTO_FILE_NAME = StringUtil.getUniqueString() + Constants.IMAGE_FILE_SUFFIX;
            LogUtils.d(TAG, "initCropFile--ExternalStorageState:" + state);
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                mFileTemp = new File(FileUtils.getTempCacheDir(), TEMP_PHOTO_FILE_NAME);
            } else {
                mFileTemp = new File(Application.instance.getFilesDir(), TEMP_PHOTO_FILE_NAME);
            }
            if (!mFileTemp.exists()) {
                mFileTemp.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拍照并回调
     */
    public static void captureForResult(Context context, int requestCode) {
        if (android.os.Build.MANUFACTURER.equalsIgnoreCase("xiaomi")) {
            ImageUtils.TEMP_PHOTO_FILE_NAME = StringUtil.getUniqueString() + Constants.IMAGE_FILE_SUFFIX;
            Uri uri = Uri.fromFile(new File(FileUtils.getTempCacheDir(), ImageUtils.TEMP_PHOTO_FILE_NAME));
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            ((Activity) context).startActivityForResult(intent, requestCode);
        } else {
            initCropFile();
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try {
                //            Uri mImageCaptureUri = null;
                //            String state = Environment.getExternalStorageState();
                //            if (Environment.MEDIA_MOUNTED.equals(state)) {
                //                mImageCaptureUri = Uri.fromFile(mFileTemp);
                //            } else {
                //                /*
                //                 * The solution is taken from here: http://stackoverflow.com/questions/10042695/how-to-get-camera-result-as-a-uri-in-data-folder
                //                 */
                //                mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
                //            }
                Uri mImageCaptureUri = Uri.fromFile(mFileTemp);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                intent.putExtra("outputX", 100);
                intent.putExtra("outputY", 100);
                intent.putExtra("return-data", true);
                ((Activity) context).startActivityForResult(intent, requestCode);
            } catch (ActivityNotFoundException e) {
                ToastUtil.getInstance().showToast(context, "无法获取图片", Toast.LENGTH_SHORT);
            }
        }
    }

    /**
     * 拍照并回调
     */
    public static void captureForResult(Fragment activity, int requestCode) {
        if (android.os.Build.MANUFACTURER.equalsIgnoreCase("xiaomi")) {
            ImageUtils.TEMP_PHOTO_FILE_NAME = StringUtil.getUniqueString() + Constants.IMAGE_FILE_SUFFIX;
            Uri uri = Uri.fromFile(new File(FileUtils.getTempCacheDir(), ImageUtils.TEMP_PHOTO_FILE_NAME));
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            activity.startActivityForResult(intent, requestCode);
        } else {
            initCropFile();
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try {
                //            Uri mImageCaptureUri = null;
                //            String state = Environment.getExternalStorageState();
                //            if (Environment.MEDIA_MOUNTED.equals(state)) {
                //                mImageCaptureUri = Uri.fromFile(mFileTemp);
                //            } else {
                //                /*
                //                 * The solution is taken from here: http://stackoverflow.com/questions/10042695/how-to-get-camera-result-as-a-uri-in-data-folder
                //                 */
                //                mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
                //            }
                Uri mImageCaptureUri = Uri.fromFile(mFileTemp);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                intent.putExtra("outputX", 100);
                intent.putExtra("outputY", 100);
                intent.putExtra("return-data", true);
                activity.startActivityForResult(intent, requestCode);
            } catch (ActivityNotFoundException e) {
                ToastUtil.getInstance().showToast(activity.getActivity(), "无法获取图片", Toast.LENGTH_SHORT);
            }
        }
    }

    /**
     * 截图并回调
     *
     * @param fragment
     * @param requestCode
     */
    public static void cropImage(Fragment fragment, int requestCode) {
        if (fragment == null) {
            return;
        }
        if (mFileTemp == null) {
            ToastUtil.getInstance().showToast(fragment.getActivity(), "图片处理错误");
            return;
        }
        //        Intent intent = new Intent(fragment.getActivity(), ActivityCropImage.class);
        //        intent.putExtra(ActivityCropImage.IMAGE_PATH, mFileTemp.getPath());
        //        intent.putExtra(ActivityCropImage.SCALE, true);
        //        intent.putExtra(ActivityCropImage.ASPECT_X, 2);
        //        intent.putExtra(ActivityCropImage.ASPECT_Y, 1);
        //        intent.putExtra(ActivityCropImage.OUTPUT_X, CROP_IMAGE_SIZE);// 设置图片大小
        //        intent.putExtra(ActivityCropImage.OUTPUT_Y, CROP_IMAGE_SIZE);
        //        fragment.startActivityForResult(intent, requestCode);

        LogUtils.d(TAG, "cropImage--mFileTemp:" + mFileTemp);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(mFileTemp), "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 3);
        intent.putExtra("aspectY", 3);
        intent.putExtra("outputX", CROP_IMAGE_SIZE);
        intent.putExtra("outputY", CROP_IMAGE_SIZE);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFileTemp));
        fragment.startActivityForResult(intent, requestCode);
    }

    /**
     * 截图并回调
     */
    public static void cropImage(SelectImageListener listener) {
        listener.onSelectDone();
    }

    /**
     * 相册图片截图，并回调
     */
    public static void galleryResultCropImage(Fragment fragment, Uri uri, SelectImageListener listener) {
        try {
            if (null != fragment && null != fragment.getActivity() && null != uri) {
                InputStream inputStream = fragment.getActivity().getContentResolver().openInputStream(uri);
                LogUtils.d(TAG, "getCorpFile:" + getCropFile());
                initCropFile();
                FileOutputStream fileOutputStream = new FileOutputStream(getCropFile());
                copyStream(inputStream, fileOutputStream);
                fileOutputStream.close();
                inputStream.close();
                listener.onSelectDone();
            } else {
                ToastUtil.getInstance().showToast(Application.instance, R.string.image_format_fail, Toast.LENGTH_LONG);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error while creating temp file", e);
            if (null != listener) {
                listener.onSelectFail();
            }
        }
    }

    /**
     * 相册图片截图，并回调
     */
    public static void galleryResultCropImage(Context context, Uri uri, SelectImageListener listener) {
        try {
            if (null != context && null != uri) {
                InputStream inputStream = context.getContentResolver().openInputStream(uri);
                LogUtils.d(TAG, "getCorpFile:" + getCropFile());
                initCropFile();
                FileOutputStream fileOutputStream = new FileOutputStream(getCropFile());
                copyStream(inputStream, fileOutputStream);
                fileOutputStream.close();
                inputStream.close();
                listener.onSelectDone();
            } else {
                ToastUtil.getInstance().showToast(Application.instance, R.string.image_format_fail, Toast.LENGTH_LONG);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error while creating temp file", e);
            if (null != listener) {
                listener.onSelectFail();
            }
        }
    }

    /**
     * 相册图片截图，并回调
     */
    public static void galleryResultCropImage(Fragment fragment, Uri uri, int requestCode) {
        try {
            if (null != fragment && null != fragment.getActivity() && null != uri) {
                InputStream inputStream = fragment.getActivity().getContentResolver().openInputStream(uri);
                FileOutputStream fileOutputStream = new FileOutputStream(getCropFile());
                copyStream(inputStream, fileOutputStream);
                fileOutputStream.close();
                inputStream.close();
                cropImage(fragment, requestCode);
            } else {
                ToastUtil.getInstance().showToast(Application.instance, "该照片格式有误,请重选!");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error while creating temp file", e);
        }
    }

    /**
     * 获取截图文件
     *
     * @return
     */
    public static File getCropFile() {
        return mFileTemp;
    }

    public static void copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    }

    /**
     * 获取图片路径
     *
     * @param context
     * @return
     */
    public static List<String> getImagePaths(Context context) {
        List<String> imagePaths = new ArrayList<String>();
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Images.ImageColumns.MIME_TYPE, MediaStore.Images.ImageColumns.DATA};
        String order = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"; // 按时间排序
        Cursor cursor = resolver.query(uri, projection, null, null, order);
        //        Log.e("ImageUtil", "count = " + cursor.getCount());
        while (cursor.moveToNext()) {
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
            if (path != null) {
                imagePaths.add(path);
            }
        }
        return imagePaths;
    }

    /**
     * 获取图片路径，封装成需要的Bean对象
     *
     * @param context
     * @param selectedList 已经选中的图片
     * @return
     */
    public static List<ImageBean> getImagePaths(Context context, List<String> selectedList) {
        List<ImageBean> imagePaths = new ArrayList<ImageBean>();
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Images.ImageColumns.MIME_TYPE, MediaStore.Images.ImageColumns.DATA};
        String order = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"; // 按时间排序
        Cursor cursor = resolver.query(uri, projection, null, null, order);
        //        Log.e("ImageUtil", "count = " + cursor.getCount());
        while (cursor.moveToNext()) {
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
            if (path != null) {
                ImageBean imageBean = new ImageBean();
                imageBean.setUrl(path);
                imagePaths.add(imageBean);
                imageBean.setChecked(false);
                setCheckBoxStatus(imageBean, selectedList);
            }
        }
        return imagePaths;
    }

    /**
     * 获取图片路径，封装成需要的Bean对象
     *
     * @param context
     * @param selectedList 已经选中的图片
     * @return
     */
    public static List<ImageBean> getLocalImages(Context context, List<ChoosableImage> selectedList) {
        if (context == null) {
            return new ArrayList<>();
        }
        List<ImageBean> imagePaths = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Images.ImageColumns.MIME_TYPE, MediaStore.Images.Thumbnails.DATA, MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.DATE_TAKEN};

        String order = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"; // 按时间排序
        Cursor cursor = resolver.query(uri, projection, null, null, order);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        String path;
        long dateTaken;
        File imgFile;
        while (cursor != null && cursor.moveToNext()) {
            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
            if (path.startsWith(context.getCacheDir().getAbsolutePath()) || StringUtil.isEmpty(path) || path.endsWith(Constants.IMAGE_GIF_SUFFIX)) {
                continue;
            }
            imgFile = new File(path);
            if (!imgFile.exists()) {
                continue;
            }
            dateTaken = imgFile.lastModified();
            BitmapFactory.decodeFile(path, options);
            if (options.outWidth < 250 || options.outWidth < 250) {
                continue;
            }
            String thumbNail = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
            if (!TextUtils.isEmpty(path)) {
                ImageBean imageBean = new ImageBean();
                ChoosableImage choosableImage = new ChoosableImage();
                imageBean.setThumbnailPath(thumbNail);
                choosableImage.thumbnailPath = thumbNail;
                choosableImage.localPath = path;
                if (null != selectedList && selectedList.contains(choosableImage)) {
                    imageBean.setChecked(true);
                } else {
                    imageBean.setChecked(false);
                }
                imageBean.setDateTaken(dateTaken);
                imageBean.setUrl(path);
                imagePaths.add(imageBean);
            }
        }
        try {
            System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
            Collections.sort(imagePaths);
        } catch (Exception e) {
            CrashReporterUtils.postCatchedException(new Throwable(e.getMessage() + ""));
        }
        return imagePaths;
    }

    /**
     * 设置checkbox状态
     */
    public static void setCheckBoxStatus(ImageBean imageBean, List<String> selectedList) {
        if (selectedList != null && selectedList.size() > 0) {
            for (int i = 0; i < selectedList.size(); i++) {
                if (imageBean.getUrl().equals(selectedList.get(i))) {
                    imageBean.setChecked(true);
                    return;
                }
                imageBean.setChecked(false);
            }
        } else {
            imageBean.setChecked(false);
        }
    }

    public interface SelectImageListener {
        void onSelectDone();

        void onSelectFail();
    }

}
